package com.huopaolan.yohuoshop.Dao.Service;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.huopaolan.yohuoshop.Dao.Utils.DBUtils;

public class DBService extends Service implements DBServiceInterface {
    //数据库
    private DBUtils dbUtils;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //懒汉式
    private static DBService dbService;

    private DBService() {
    }

    public static DBService getDbService() {
        //单例效验双重锁
        if (dbService == null) {
            synchronized (DBService.class) {
                if (dbService == null) {
                    dbService = new DBService();
                }
            }
        }
        return dbService;
    }

    private Context context;

    public void init(Context context) {
        this.context = context;
        dbUtils = new DBUtils(context);
    }

    @Override
    public long insert(String userName, ContentValues values) {
        if (TextUtils.isEmpty(userName) || values == null) {
            return 0;
        }
        return dbUtils.insert(userName, values);
    }

    @Override
    public int delete(String userName, String whereClause, String[] whereArgs) {
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(whereClause) || whereArgs == null) {
            return 0;
        }
        return dbUtils.delete(userName, whereClause, whereArgs);
    }

    @Override
    public int update(String userName, ContentValues values, String whereClause, String[] whereArgs) {
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(whereClause) || values == null || whereArgs == null) {
            return 0;
        }
        return dbUtils.update(userName, values, whereClause, whereArgs);
    }

    @Override
    public Cursor query(String userName, String whereClause, String[] whereArgs) {
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(whereClause) || whereArgs == null) {
            return null;
        }
        return dbUtils.query(userName, whereClause, whereArgs);
    }

    @Override
    public void close() {
        dbUtils.close();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
